package io.github.leon406.view.dialog

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.View
import android.widget.TextView
import io.github.leon406.ext.onClick
import io.github.leon406.ext.visibleGone
import me.leon.ext.android.extra
import me.leon.ui.R

open class IosStyleDialog : AbsDialog() {
    companion object {
        private const val TITLE = "title"
        private const val CONTENT = "content"
        private const val SHOW_CANCEL = "showCancel"
        private const val AUTO_DISMISS = "autoDismiss"
        private const val CONFIRM_STRING = "confirmStr"
        private const val CANCEL_STRING = "cancelStr"
        fun newInstance(
            title: String,
            content: String,
            showCancel: Boolean = true,
            autoDismiss: Boolean = true,
            cancelStr: String = "",
            confirmStr: String = ""
        ): IosStyleDialog {
            val args = Bundle()
            val fragment = IosStyleDialog()
            args.putString(TITLE, title)
            args.putString(CONTENT, content)
            args.putString(CANCEL_STRING, cancelStr)
            args.putString(CONFIRM_STRING, confirmStr)
            args.putBoolean(SHOW_CANCEL, showCancel)
            args.putBoolean(AUTO_DISMISS, autoDismiss)
            fragment.arguments = args
            fragment.isCancelable = showCancel
            return fragment
        }
    }

    override fun bindLayout() = R.layout.dialog_ios_choose

    private val title: String by extra("")
    private val content: String by extra("")
    private val showCancel: Boolean by extra(true)
    private val autoDismiss: Boolean by extra(true)
    private val cancelStr: String by extra("")
    private val confirmStr: String by extra("")
    override fun initDialog() {

        getView<TextView>(R.id.tvConfirm)
            .apply {
                if (confirmStr.isNotEmpty()) {
                    text = confirmStr
                }
            }
            .onClick(1500) {
                if (autoDismiss) {
                    dismiss()
                }
                callback?.confirm()
            }

        getView<TextView>(R.id.tvTitle).apply {
            text = title
            visibility = View.VISIBLE.takeIf { title.isNotEmpty() } ?: View.GONE
        }
        getView<View>(R.id.vSplit).visibleGone(showCancel)
        getView<View>(R.id.tvCancel).visibleGone(showCancel)

        getView<TextView>(R.id.tvContent).movementMethod = ScrollingMovementMethod()
        setText(R.id.tvContent, content)
        getView<TextView>(R.id.tvCancel).apply {
            if (cancelStr.isNotEmpty()) {
                text = cancelStr
            }
            setOnClickListener {
                dismiss()
                callback?.cancel()
            }
        }
    }
}
